import Vue from 'vue'
import axios from 'axios'
import router from "../router";
// 创建实例
const instance = axios.create({});
// 基础配置
instance.defaults.baseURL = 'http://localhost:3000/api/admin/';
instance.defaults.timeout = 10000; // 超时时间
instance.defaults.withCredentials = false; // 是否允许携带cookie

// 请求拦截
instance.interceptors.request.use(config => {
    if (localStorage.token) {
        config.headers.Authorization = "Bearer " + localStorage.token || ""
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截
instance.interceptors.response.use(response => {
    return response
}, error => {
    if (error.response && error.response.data) {
        Vue.prototype.$message({
            type: "error",
            message: error.response.data
        })
    }
    if (error.response.status === 401) {
        router.push("/login")
    }
})
Vue.prototype.$http = instance;
export default instance;